#include "MatlabSolver.h"
#include <debug.h>

#pragma comment( lib, "libmx.lib" )
#pragma comment( lib, "libeng.lib" )

namespace CGF{

	MatlabTool::~MatlabTool()
	{
		std::map<std::string, mxArray*>::const_iterator it;
		for(it = variables.begin();
			it != variables.end();
			it++
			)
			mxDestroyArray(it->second);
		
		exe_command("clear all;");

		if(matlabEngine)		
		 engClose(matlabEngine);
	}

	bool MatlabTool::connect_matlab()
	{
		    matlabEngine = engOpen("\0");
			if (NULL == matlabEngine) {
				fprintf(stderr, "Could not initialize the engine.\n");
				return false;
			}
			exe_command("clear all;");
			return true;
    }

	bool MatlabTool::exe_command(const char *command, bool outPut)
	{
		return exe_command(std::string(command),outPut);
	}
	bool MatlabTool::exe_command(std::string &command, bool outPut)
	{
		dbg(-1) <<"do : " <<command;
		 bool ret = engEvalString(matlabEngine, command.c_str());
		
		 if(outPut)
		 {
			size_t szOutputBuffer = 65536;
			char* matlabOutputBuffer = new char[szOutputBuffer];
			 matlabOutputBuffer[szOutputBuffer-1] = '\0';

			engOutputBuffer(matlabEngine, matlabOutputBuffer, szOutputBuffer);
			 engEvalString(matlabEngine, "whos");
			 dbg(-1)<<matlabOutputBuffer;

			 engOutputBuffer(matlabEngine, NULL, 0);
			 delete[] matlabOutputBuffer;
		 }
		return !ret;
	}

	//bool  MatlabTool::set_variable(const char * name,const int &m, const int &n)
	//{
	//	return set_variable(std::string(name),m,n);
	//}
	//bool  MatlabTool::set_variable(std::string & name,const int &m, const int &n)
	//{
	//	if(variables.count(name)==0)
	//	{
	//		mxArray* var = mxCreateNumericMatrix(m, n, mxDOUBLE_CLASS, mxREAL);
	//		variables[name] = var;
	//
	//		engPutVariable(matlabEngine, name.c_str(), var);
	//		return true;
	//	}
	//	return false;
	//}

	//bool  MatlabSparseSolver::set_sparse_variable(const char * name,const int &m, const int &n,const int &maxValNum)
	//{
	//	
	//	if(variables.count(name)==0)
	//	{
	//		mxArray* var = mxCreateSparse(m, n, maxValNum, mxREAL);
	//		variables[name] = var;
	//
	//		engPutVariable(matlabEngine, name, var);
	//		return true;
	//	}
	//	return false;
	//}
}